package co.yixiang.modules.shop.rest.Arest;

import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import co.yixiang.exception.BadRequestException;
import co.yixiang.exception.ErrorRequestException;
import co.yixiang.modules.shop.domain.YxUser;
import co.yixiang.modules.shop.domain.YxUserAddress;
import co.yixiang.modules.shop.service.YxUserAddressService;
import co.yixiang.modules.shop.service.YxUserService;
import co.yixiang.modules.shop.service.dto.YxUserAddressDto;
import co.yixiang.modules.shop.service.dto.YxUserAddressQueryCriteria;
import co.yixiang.modules.shop.service.dto.YxUserDto;
import co.yixiang.modules.shop.util.WechatDecryptDataUtil;
import co.yixiang.modules.shop.util.WxUtil;
import co.yixiang.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "Api2:商城:用户")
@RestController
@RequestMapping("api2/yxUser")
public class AUserController  extends ABaseController {
    @Autowired
    private YxUserService yxUserService;
    @Autowired
    private YxUserAddressService addressService;
    @Autowired
    private WxUtil wxUtil;


    @ApiOperation(value = "获取用户信息")
    @GetMapping(value = "/{id}")
    public YxUserDto getUser(@PathVariable(value = "id") String uid) {
        YxUser user = yxUserService.getById(uid);
        Assert.notNull(user);
        return generator.convert(user,YxUserDto.class);
    }

    @ApiOperation(value = "更新用户信息")
    @PostMapping(value = "/")
    public YxUser updateUser(@Validated YxUser user) {
        yxUserService.updateById(user);
        return yxUserService.getById(user.getUid());
    }

    @ApiOperation(value = "获取用户地址")
    @GetMapping(value = "/address")
    public List<YxUserAddressDto> getAddress(YxUserAddressQueryCriteria criteria) {
        List<YxUserAddress> list = addressService.queryAll(criteria);
        return generator.convert(list,YxUserAddressDto.class);
    }

    @ApiOperation(value = "登录", notes = "登录")
    @PostMapping(value = "/login")
    @ResponseBody
    public YxUserDto login(@RequestParam(value = "session_key",required = false) String skey, String code) {
        if(StringUtils.isEmpty(skey) && StringUtils.isEmpty(code)){
            throw new BadRequestException("参数错误");
        }

        //查询code
        if(StringUtils.isEmpty(skey) && StringUtils.isNotEmpty(code)){
            //获取openid skey
            String res = wxUtil.code2Session(code);
            JSONObject jsonObject = JSONUtil.parseObj(res);
            Object openid = jsonObject.get("openid");
            if(openid==null){
                throw new ErrorRequestException("微信服务器响应错误："+jsonObject.toString());
            }
            YxUser one = yxUserService.getOne(new LambdaQueryWrapper<YxUser>()
                    .eq(YxUser::getOpenId, openid));
            if(one == null){
                //插入默认用户信息
                one = new YxUser();
                one.setOpenId((String) openid);
                one.setWxSession(jsonObject.get("session_key").toString());
                yxUserService.insertDefault(one);
            }
            return generator.convert(one,YxUserDto.class);
        }else{
            //sessionKey不为空，返回查询结果
            YxUser one = yxUserService.getOne(new LambdaQueryWrapper<YxUser>()
                    .eq(YxUser::getWxSession,skey));
            if(one == null){
                throw new BadRequestException("查询不到用户");
            }
            return generator.convert(one,YxUserDto.class);
        }

    }


    @ApiOperation(value = "获取手机号", notes = "获取手机号")
    @PostMapping(value = "/phone",produces = {"text/plain;charset=UTF-8", "application/*;charset=UTF-8"})
    @ResponseBody
    public Object getPhone(@RequestBody String body){
        JSONObject jsonObject = JSONUtil.parseObj(body);
        String  encryptedData;
        String  iv;
        String sessionKey;
        try {
            encryptedData = jsonObject.get("encryptedData").toString();
            iv = jsonObject.get("iv").toString();
            sessionKey = jsonObject.get("sessionKey").toString();
        }catch (NullPointerException e){
            throw new BadRequestException("传入数据字段有误");
        }

        try {
            String data = WechatDecryptDataUtil.decryptData(encryptedData, sessionKey, iv);
            JSONObject dataObject = JSONUtil.parseObj(data);
            return ResponseEntity.ok(dataObject);
        }catch (Exception e){
            throw new BadRequestException("解密失败，可能为sessionKey无效");
        }

    }

}
